<template>
  <el-dialog
    v-model="visible"
    :append-to-body="true"
    top="6vh"
    :close-on-click-modal="false"
    @close="handleClose"
    width="720px"
    class="unified-dialog environment-form-dialog"
  >
    <template #header>
      <DialogHeader
        :icon="getServiceIcon(formData.service_type)"
        :title="isEdit ? '编辑服务配置' : '添加服务配置'"
        :description="isEdit ? '修改现有服务的连接配置' : '创建新的服务连接配置'"
        type="primary"
      />
    </template>
    
    <div class="form-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
        label-width="0"
        class="environment-form"
      >
        <!-- 基础配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Setting /></el-icon>
            <span>基础配置</span>
          </div>
          
          <div class="form-grid">
            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">服务类型</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="service_type">
                <el-select 
                  v-model="formData.service_type" 
                  placeholder="选择服务类型"
                  popper-class="batch-dialog-select-popper"
                  :teleported="true"
                >
                  <el-option label="Flink" value="flink">
                    <div class="option-content">
                      <el-icon><Connection /></el-icon>
                      <span>Flink</span>
                    </div>
                  </el-option>
                  <el-option label="Redis" value="redis">
                    <div class="option-content">
                      <el-icon><CirclePlus /></el-icon>
                      <span>Redis</span>
                    </div>
                  </el-option>
                  <el-option label="MySQL" value="mysql">
                    <div class="option-content">
                      <el-icon><DataLine /></el-icon>
                      <span>MySQL</span>
                    </div>
                  </el-option>
                  <el-option label="StarRocks" value="starrocks">
                    <div class="option-content">
                      <el-icon><Star /></el-icon>
                      <span>StarRocks</span>
                    </div>
                  </el-option>
                  <el-option label="Kafka" value="kafka">
                    <div class="option-content">
                      <el-icon><Message /></el-icon>
                      <span>Kafka</span>
                    </div>
                  </el-option>
        </el-select>
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">配置名称</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="name">
        <el-input
          v-model="formData.name"
                  placeholder="如：默认环境、测试环境"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Edit /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>
          </div>
        </div>

        <!-- 连接配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Link /></el-icon>
            <span>连接配置</span>
          </div>
          
          <div class="form-grid">
            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">主机地址</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="host">
        <el-input
          v-model="formData.host"
                  placeholder="如：10.1.1.68 或 localhost"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Monitor /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">端口</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="port">
                <el-input-number
                  v-model="formData.port"
          :min="1"
          :max="65535"
                  placeholder="端口号"
                  controls-position="right"
                  style="width: 100%"
        />
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">协议</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="protocol">
                <el-select 
                  v-model="formData.protocol" 
                  placeholder="选择协议"
                  popper-class="batch-dialog-select-popper"
                  :teleported="true"
                >
                  <el-option label="HTTP" value="http">
                    <div class="option-content">
                      <el-icon><Link /></el-icon>
                      <span>HTTP</span>
                    </div>
                  </el-option>
                  <el-option label="HTTPS" value="https">
                    <div class="option-content">
                      <el-icon><Lock /></el-icon>
                      <span>HTTPS</span>
                    </div>
                  </el-option>
                  <el-option label="TCP" value="tcp">
                    <div class="option-content">
                      <el-icon><Connection /></el-icon>
                      <span>TCP</span>
                    </div>
                  </el-option>
        </el-select>
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">路径</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="path">
        <el-input
          v-model="formData.path"
                  placeholder="如：/ 或 /api"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Folder /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>
          </div>

          <div class="connection-preview">
            <div class="preview-label">连接地址预览：</div>
            <div class="preview-url">
              {{ `${formData.protocol}://${formData.host || 'host'}:${formData.port || 'port'}${formData.path || '/'}` }}
            </div>
          </div>
        </div>

        <!-- 认证配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Key /></el-icon>
            <span>认证配置</span>
            <span class="section-subtitle">（可选）</span>
          </div>
          
          <div class="form-grid">
            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">用户名</span>
              </label>
              <el-form-item prop="username">
        <el-input
          v-model="formData.username"
                  placeholder="请输入用户名"
                  clearable
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">密码</span>
              </label>
              <el-form-item prop="password">
        <el-input
          v-model="formData.password"
          type="password"
                  placeholder="请输入密码"
          show-password
                  clearable
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>

            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">数据库</span>
              </label>
              <el-form-item prop="database">
        <el-input
          v-model="formData.database"
                  placeholder="请输入数据库名称"
                  clearable
                >
                  <template #prefix>
                    <el-icon><DataLine /></el-icon>
                  </template>
                </el-input>
      </el-form-item>
            </div>
          </div>
        </div>

        <!-- 附加配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><MoreFilled /></el-icon>
            <span>附加配置</span>
          </div>
          
          <div class="form-grid">
            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">描述</span>
              </label>
              <el-form-item prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
                  placeholder="请输入服务描述信息"
                  resize="none"
                  maxlength="200"
                  show-word-limit
        />
      </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">排序</span>
              </label>
              <el-form-item prop="sort_order">
        <el-input-number
          v-model="formData.sort_order"
          :min="0"
                  placeholder="排序值"
                  controls-position="right"
          style="width: 100%"
        />
        <div class="form-tip">数字越小排序越靠前</div>
      </el-form-item>
            </div>
          </div>
        </div>
    </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="footer-left">
          <el-button 
            :loading="testLoading" 
            @click="handleTestConnection"
            :disabled="!canTestConnection"
          >
            <el-icon v-if="!testLoading"><Connection /></el-icon>
            {{ testLoading ? '测试中...' : '测试连接' }}
          </el-button>
          <span v-if="testResult" :class="['test-result', testResult.success ? 'success' : 'error']">
            {{ testResult.message }}
          </span>
        </div>
        <div class="footer-right">
          <el-button @click="handleClose">取消</el-button>
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleSubmit"
            class="submit-btn"
          >
            <el-icon v-if="!loading"><component :is="isEdit ? 'Edit' : 'Plus'" /></el-icon>
            {{ isEdit ? '更新配置' : '添加配置' }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { componentLogger } from '@/utils/logger'
import api from '@/utils/api'
import { 
  Connection, Setting, Link, Monitor, Lock, Key, User, DataLine, 
  Folder, Edit, Plus, Star, Message, CirclePlus, More, MoreFilled
} from '@element-plus/icons-vue'
import DialogHeader from '@/components/DialogHeader.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  environment: {
    type: Object,
    default: () => ({})
  },
  existingNames: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'submit'])

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const testLoading = ref(false)
const testResult = ref(null)
const formRef = ref()

// 表单数据
const formData = reactive({
  service_type: 'flink',
  name: '',
  host: '',
  port: null,
  protocol: 'http',
  path: '/',
  username: '',
  password: '',
  database: '',
  description: '',
  sort_order: 0
})

// 表单验证规则
const rules = {
  service_type: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '配置名称长度在 2 到 50 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 检查配置名称是否已存在（排除当前编辑的配置）
        const isDuplicate = props.existingNames.some(name => 
          name === value && name !== props.environment.name
        )
        if (isDuplicate) {
          callback(new Error('配置名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' },
    {
      pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^[a-zA-Z0-9.-]+$/,
      message: '请输入有效的主机地址',
      trigger: 'blur'
    }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号范围为 1-65535', trigger: 'blur' }
  ],
  protocol: [
    { required: true, message: '请选择协议', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路径', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.environment.name)

// 是否可以测试连接
const canTestConnection = computed(() => {
  return !!(formData.host && formData.port && formData.protocol)
})

// 获取服务图标
const getServiceIcon = (serviceType) => {
  const iconMap = {
    flink: 'Connection',
    redis: 'CirclePlus',
    mysql: 'DataLine',
    starrocks: 'Star',
    kafka: 'Message'
  }
  return iconMap[serviceType] || 'Connection'
}

// 监听器
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    initFormData()
    testResult.value = null
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 监听表单数据变化，清除测试结果
watch(formData, () => {
  testResult.value = null
})

// 方法
const initFormData = () => {
  if (props.environment.name) {
    // 编辑模式
    Object.assign(formData, {
      service_type: props.environment.service_type || 'flink',
      name: props.environment.name,
      host: props.environment.host || '',
      port: props.environment.port || null,
      protocol: props.environment.protocol || 'http',
      path: props.environment.path || '/',
      username: props.environment.username || '',
      password: props.environment.password || '',
      database: props.environment.database || '',
      description: props.environment.description || '',
      sort_order: props.environment.sort_order || 0
    })
  } else {
    // 新增模式
    Object.assign(formData, {
      service_type: 'flink',
      name: '',
      host: '',
      port: null,
      protocol: 'http',
      path: '/',
      username: '',
      password: '',
      database: '',
      description: '',
      sort_order: 0
    })
  }
  
  // 清除验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

const handleClose = () => {
  visible.value = false
}

const handleTestConnection = async () => {
  try {
    testLoading.value = true
    testResult.value = null
    
    const testData = {
      service_type: formData.service_type,
      host: formData.host,
      port: formData.port,
      protocol: formData.protocol,
      path: formData.path,
      username: formData.username,
      password: formData.password,
      database: formData.database
    }
    
    const response = await api.post('/settings/test-connection', testData)
    
    if (response.data.success) {
      testResult.value = {
        success: true,
        message: '✓ 连接成功'
      }
      ElMessage.success('连接测试成功')
    } else {
      testResult.value = {
        success: false,
        message: `✗ ${response.data.error || '连接失败'}`
      }
    }
  } catch (error) {
    componentLogger.error('连接测试失败:', error)
    testResult.value = {
      success: false,
      message: `✗ ${error.response?.data?.error || error.message || '连接失败'}`
    }
    ElMessage.error(`连接测试失败: ${error.response?.data?.error || error.message}`)
  } finally {
    testLoading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    const submitData = {
      ...formData,
      port: formData.port || 8081
    }
    
    emit('submit', submitData)
  } catch (error) {
    componentLogger.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 暴露方法
defineExpose({
  setLoading: (val) => {
    loading.value = val
  }
})
</script>

<style scoped>
/* 对话框样式 */
.environment-form-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

/* 对话框已使用统一样式系统 (dialog-system.css) */

/* 自定义布局样式 */
.environment-form-dialog :deep(.el-dialog__body) {
  padding: 0;
  max-height: 70vh;
  overflow-y: auto;
}

/* 表单容器 */
.form-container {
  padding: 20px;
  max-height: calc(70vh - 140px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.environment-form {
  max-width: none;
}

/* 表单区域 */
.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-subtitle {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

/* 表单网格 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 20px;
}

.form-item-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item-wrapper.full-width {
  grid-column: 1 / -1;
}

/* 表单标签 */
.form-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.label-text {
  flex: 1;
}

.required-mark {
  color: #f56c6c;
  font-weight: 600;
}

/* 选项内容 */
.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-content .el-icon {
  color: #409eff;
}

/* 连接预览 */
.connection-preview {
  grid-column: 1 / -1;
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.preview-label {
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.preview-url {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #d9ecff;
  word-break: break-all;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.footer-right {
  display: flex;
  gap: 12px;
}

.test-result {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 4px;
}

.test-result.success {
  color: #67c23a;
  background: #f0f9ff;
}

.test-result.error {
  color: #f56c6c;
  background: #fef0f0;
}

.submit-btn {
  min-width: 120px;
}

/* 表单项样式覆盖 */
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__error) {
  position: static;
  margin-top: 4px;
}

:deep(.el-input .el-input__inner) {
  height: 36px;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

:deep(.el-input .el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-select .el-input .el-input__inner) {
  height: 36px;
}

:deep(.el-input-number .el-input__inner) {
  height: 36px;
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  resize: none;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-input__prefix) {
  color: #909399;
}

:deep(.el-input .el-input__prefix) {
  left: 12px;
}

:deep(.el-input.el-input--prefix .el-input__inner) {
  padding-left: 40px;
}

/* 滚动条样式 */
.form-container::-webkit-scrollbar {
  width: 6px;
}

.form-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .environment-form-dialog :deep(.el-dialog) {
    width: 95vw !important;
    margin: 0 auto;
  }
  
  .form-container {
    padding: 16px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .form-item-wrapper.full-width {
    grid-column: 1;
  }
}

/* 动画效果 */
.form-section {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
.environment-form-dialog :deep(.el-dialog__body)::-webkit-scrollbar {
  width: 6px;
}

.environment-form-dialog :deep(.el-dialog__body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.environment-form-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.environment-form-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
